<script setup lang="ts">
  import { ref, reactive, watch, computed } from 'vue';
  import { TableRowSelection, Notification } from '@arco-design/web-vue';
  import { getUserJob } from '@/utils/auth';
  import { useBooleanStore } from '@/store';
  import {
    searchDeliverPlan,
    searchProblemType,
    insertDto,
  } from '@/api/material-receipt';

  const booleanStore = useBooleanStore();
  const hStyle = ref({
    'background-color': booleanStore.color,
    'border-radius': booleanStore.borderRadius,
  });
  const showDrawer = ref<boolean>(false);
  const columns: any[] = [
    {
      title: '序号',
      dataIndex: 'PAGEHELPER_ROW_ID',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '需求单位',
      dataIndex: 'requireShop',
    },
    {
      title: '条码',
      dataIndex: 'barcode',
    },
    {
      title: '交接单号',
      dataIndex: 'deliveryPlanCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '合格证信息',
      dataIndex: 'mesCheckQualiticationId',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '物料名称',
      dataIndex: 'itemName',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '机型',
      dataIndex: 'productCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '图号',
      dataIndex: 'itemCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },

    {
      title: '型号',
      dataIndex: 'mProductNumber',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '质量编号',
      dataIndex: 'qualityCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },

    {
      title: '批次',
      dataIndex: 'batchNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '架次',
      dataIndex: 'startLotNo',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },

    {
      title: '数量',
      dataIndex: 'deliveryQty',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '计量单位',
      dataIndex: 'mdsUnit',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '物料大类',
      dataIndex: 'itemType',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },

    {
      title: '制造单位',
      dataIndex: 'attribute18',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '移交人工号',
      dataIndex: 'empName',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
    {
      title: '移交时间',
      dataIndex: 'deliveryDate',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
    },
  ];
  const localTableData = ref<any[]>([]);
  const rowSelection: TableRowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const selectedKeys = ref<any>([]);

  const barcode = ref<string>('');
  const mProductNumber = ref<string>('');
  const qualityCode = ref<string>('');
  const wuliaoNum = ref<string>('');
  const jixing = ref<string>('');
  const pici = ref<string>('');
  const deliveryEmpCode = ref<string>('');
  const startTime = ref<string>('');
  const endTime = ref<string>('');

  // 数据库一共有多少条
  const total = ref<number>(0);
  const pageNumber = ref<number>(1);
  const pageSize = ref<number>(10);

  // 问题类型

  const problemTypeList = ref<any[]>([]);

  const form = ref({
    problemType: '',
    problemContent: '',
  });

  const flowQueryData = ref({
    searchParams: computed(() => ({
      barcode: barcode.value,
      productCode: jixing.value,
      batchNo: pici.value,
      itemCode: wuliaoNum.value,
      qualityCode: qualityCode.value,
      deliveryEmpCode: deliveryEmpCode.value,
      startTime: startTime.value,
      endTime: endTime.value,
      mProductNumber: mProductNumber.value,
    })),
    pageParameter: computed(() => ({
      rows: pageSize.value,
      page: pageNumber.value,
    })),
  });

  async function search() {
    const data = await searchDeliverPlan(flowQueryData.value);
    localTableData.value = data?.responseBody?.result || [];
    total.value = data?.responseBody?.pageParameter?.totalCount || 0;
  }
  async function getProblemType() {
    const data = await searchProblemType('');
    problemTypeList.value = data.responseBody;
  }
  function reset() {
    barcode.value = '';
    mProductNumber.value = '';
    qualityCode.value = '';
    wuliaoNum.value = '';
    jixing.value = '';
    pici.value = '';
    deliveryEmpCode.value = '';
    startTime.value = '';
    endTime.value = '';
    // search();
  }
  // 监听弹框
  watch(
    () => booleanStore.boolValue,
    (newValue: boolean) => {
      if (!newValue) {
        showDrawer.value = newValue;
        localTableData.value = [];
        total.value = 0;
        return;
      }
      if (booleanStore.num === 1) {
        showDrawer.value = newValue;
        // search();
        getProblemType();
        barcode.value = '';
        mProductNumber.value = '';
        qualityCode.value = '';
        wuliaoNum.value = '';
        jixing.value = '';
        pici.value = '';
        deliveryEmpCode.value = '';
        startTime.value = '';
        endTime.value = '';
        localTableData.value = [];
        selectedKeys.value = [];
        form.value.problemContent = '';
        form.value.problemType = '';
      }
    }
  );

  function afterVisibleChange(val: any) {
    if (!val) {
      booleanStore.toggleBool(1);
    }
  }
  function handleCancel() {
    booleanStore.toggleBool(1);
  }

  // 文本框验证
  const formRef = ref<any>('');
  // 问题输入框的规则
  const rules = {
    problemContent: [
      { required: true, message: '不能为空' },
      {
        validator: (value: any, cb: any) => {
          if (value && value.length > 100) {
            cb('不能超过 100位字符');
          } else {
            cb();
          }
        },
      },
    ],
    problemType: [{ required: true, message: '不能为空' }],
  };

  async function handleOk(done: any) {
    const res = await formRef.value.validate();
    if (res) {
      done(false);
    } else {
      if (selectedKeys.value.length === 0) {
        Notification.warning({
          title: '提示',
          content: '请选择交接单',
          closable: true,
        });
        return;
      }

      const selectedData = localTableData.value.filter((item: any) =>
        selectedKeys.value.includes(item.PAGEHELPER_ROW_ID)
      );
      const getUserJobNumber = ref<any>(getUserJob());
      const info = {
        wmsDeliveryPlans: selectedData,
        problemType: form.value.problemType,
        problemContent: form.value.problemContent,
        applyEmpcode: getUserJobNumber.value,
      };
      const data: any = await insertDto(info);
      if (data.retCode === '200') {
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
        booleanStore.toggleBool(1);
        problemTypeList.value = [];
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
        booleanStore.toggleBool(1);
      }
      booleanStore.watchUpdate(1);
      done();
    }
  }
  function change(e: any) {
    pageNumber.value = e;
  }
  function changeSize(e: any) {
    pageSize.value = e;
  }
  watch([pageNumber, pageSize], () => {
    search();
  });
</script>

<template>
  <a-drawer
    width="70%"
    :height="340"
    :visible="showDrawer"
    placement="right"
    @after-visible-change="afterVisibleChange"
    @cancel="handleCancel"
    @ok="handleOk"
  >
    <template #title> 创建协调单 </template>
    <a-card :header-style="hStyle" :bordered="false">
      <template #title>
        <div class="font">查询条件</div>
      </template>
      <!-- 第一行 -->
      <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
        <a-col :span="6">
          <div>
            <a-input
              v-model="barcode"
              placeholder="条码"
              size="large"
              allow-clear
              @press-enter="search"
            />
          </div>
        </a-col>
        <a-col :span="6">
          <div>
            <a-input
              v-model="mProductNumber"
              placeholder="成品型号"
              size="large"
              allow-clear
              @press-enter="search"
            />
          </div>
        </a-col>
        <a-col :span="6">
          <div>
            <a-input
              v-model="qualityCode"
              placeholder="质量编号"
              size="large"
              allow-clear
              @press-enter="search"
            />
          </div>
        </a-col>
        <a-col :span="6">
          <div>
            <a-input
              v-model="wuliaoNum"
              placeholder="图号"
              size="large"
              allow-clear
              @press-enter="search"
            />
          </div>
        </a-col>
      </a-row>
      <!-- 第二行 -->
      <a-row class="row-top" :gutter="{ md: 8, lg: 24, xl: 32 }">
        <a-col :span="6">
          <div>
            <a-input
              v-model="jixing"
              placeholder="机型"
              size="large"
              allow-clear
              @press-enter="search"
            />
          </div>
        </a-col>
        <a-col :span="6">
          <div>
            <a-input
              v-model="pici"
              placeholder="批次"
              size="large"
              allow-clear
              @press-enter="search"
            />
          </div>
        </a-col>
        <a-col :span="6">
          <div>
            <a-input
              v-model="deliveryEmpCode"
              placeholder="移交人工号"
              size="large"
              allow-clear
              @press-enter="search"
            />
          </div>
        </a-col>
        <a-col :span="6">
          <div>
            <a-date-picker
              v-model="startTime"
              style="width: 100%"
              placeholder="移交时间"
              size="large"
              allow-clear
              @press-enter="search"
            />
          </div>
        </a-col>
      </a-row>

      <a-row class="row-top" :gutter="{ md: 8, lg: 24, xl: 32 }">
        <a-col :span="6">
          <div>
            <a-date-picker
              v-model="endTime"
              style="width: 100%"
              placeholder=" 到"
              size="large"
              allow-clear
              @press-enter="search"
            />
          </div>
        </a-col>
        <a-col :span="6">
          <a-button type="primary" size="large" @click="search">查询</a-button>
          <a-button class="btn-reset" size="large" @click="reset"
            >重置</a-button
          >
        </a-col>
      </a-row>
    </a-card>
    <a-card :header-style="hStyle" :bordered="false">
      <template #title>
        <div class="font">交接单数据</div>
      </template>
      <a-table
        v-model:selectedKeys="selectedKeys"
        :stripe="true"
        class="top-table"
        :pagination="false"
        row-key="PAGEHELPER_ROW_ID"
        :columns="columns"
        :data="localTableData"
        :row-selection="rowSelection"
      >
      </a-table>
      <div class="page-position">
        <a-pagination
          :total="total"
          :current="pageNumber"
          :page-size="pageSize"
          show-total
          show-jumper
          show-page-size
          @change="change"
          @update:page-size="changeSize"
        />
      </div>
    </a-card>
    <a-card :header-style="hStyle" :bordered="false">
      <template #title>
        <div class="font">选择问题</div>
      </template>

      <a-form
        ref="formRef"
        :model="form"
        :rules="rules"
        layout="inline"
        :style="{ width: 'auto' }"
      >
        <a-form-item field="problemType" label="问题类型:">
          <a-select
            v-model="form.problemType"
            placeholder="问题类型"
            size="large"
          >
            <a-option
              v-for="(item, index) in problemTypeList"
              :key="index"
              :value="item.problemTypeId"
              >{{ item.problemType }}</a-option
            >
          </a-select>
        </a-form-item>
        <a-form-item field="problemContent" label="问题内容:">
          <a-input
            v-model="form.problemContent"
            placeholder="问题内容"
            size="large"
          />
        </a-form-item>
      </a-form>
    </a-card>
    <template #footer>
      <div class="flex-btn">
        <a-button type="primary" @click="handleOk">确认</a-button>
        <a-button class="btn-reset" @click="handleCancel">取消</a-button>
      </div>
    </template>
  </a-drawer>
</template>

<style scoped>
  .top-table {
    white-space: nowrap;
  }
  .row-top {
    margin-top: 10px;
  }
  .btn-reset {
    margin-left: 10px;
  }
  .font {
    font-size: 20px;
    color: black;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }
  .flex-btn {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .flex-icon {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .icon-style {
    color: red;
    margin-right: 10px;
  }
  .page-position {
    margin-top: 20px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
